<template>
  <div class="create-picture-page">
    <a-card title="新建图片" :bordered="false">
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="本地上传">
          <a-form :model="form" :label-col="{ span: 4 }" @finish="handleSubmit">
            <!-- 上传 -->
            <a-form-item label="图片文件"
              name="file"
              :rules="[{ required: false, message: '请选择图片' }]"
            >
              <a-upload
                v-model:fileList="fileList"
                accept="image/*"
                :max-count="1"
                :before-upload="beforeUpload"
                list-type="picture-card"
                :custom-request="handleUploadChange"
              >
                <div v-if="fileList.length < 1">
                  <plus-outlined />
                  <div style="margin-top: 8px">点击或拖拽上传</div>
                </div>
              </a-upload>
              <div class="upload-tips">
                支持 JPG、PNG、WEBP 格式，大小不超过 2MB
              </div>
            </a-form-item>

            <!-- 名称 -->
            <a-form-item label="名称" name="name">
              <a-input
                v-model:value="form.name"
                placeholder="请输入图片名称"
                :maxlength="50"
                show-count
              />
            </a-form-item>

            <!-- 简介 -->
            <a-form-item label="简介" name="introduction">
              <a-textarea
                v-model:value="form.introduction"
                :rows="3"
                placeholder="请输入图片简介"
                :maxlength="200"
                show-count
              />
            </a-form-item>

            <!-- 分类 -->
            <a-form-item label="分类" name="category">
              <a-select
                v-model:value="form.category"
                placeholder="请选择分类"
                :loading="loadingTags"
                allow-clear
              >
                <a-select-option
                  v-for="category in categoryList"
                  :key="category"
                  :value="category"
                >
                  {{ category }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <!-- 标签 -->
            <a-form-item label="标签" name="tags">
              <a-select
                v-model:value="form.tags"
                mode="tags"
                placeholder="输入后回车或选择预置标签"
                style="width: 100%"
                :loading="loadingTags"
              >
                <a-select-option
                  v-for="tag in tagList"
                  :key="tag"
                  :value="tag"
                >
                  {{ tag }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <!-- 提交 -->
            <a-form-item :wrapper-col="{ offset: 4 }">
              <a-space>
                <a-button
                  type="primary"
                  html-type="submit"
                  :loading="loading"
                  :disabled="!fileList.length"
                >
                  {{ loading ? '上传中...' : '提交' }}
                </a-button>
                <a-button @click="$router.back()">返回</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="2" tab="URL上传">
          <a-form :model="form" :label-col="{ span: 4 }">
            <!-- URL输入 -->
            <a-form-item
              label="图片URL"
              name="fileUrl"
              :rules="[{ required: false, message: '请输入图片URL' }]"
            >
              <a-input-group compact style="display: flex;">
                <a-input v-model:value="fileUrl" placeholder="请输入图片 URL" style="flex: 1" />
                <a-button type="primary" :loading="urlLoading" @click="handleUploadByUrl" style="width: 120px; margin-left: 10px;">提交</a-button>
              </a-input-group>
            </a-form-item>

            <!-- 图片预览 -->
            <a-form-item label="图片预览">
              <img v-if="previewUrl" :src="previewUrl" alt="Preview" style="max-width: 100%; max-height: 300px; border: 1px solid #ddd; border-radius: 4px;" />
              <div v-else style="color: #999; font-style: italic;">请输入有效的图片URL以预览图片</div>
            </a-form-item>

            <!-- 名称 -->
            <a-form-item label="名称" name="name">
              <a-input
                v-model:value="form.name"
                placeholder="请输入图片名称"
                :maxlength="50"
                show-count
              />
            </a-form-item>

            <!-- 简介 -->
            <a-form-item label="简介" name="introduction">
              <a-textarea
                v-model:value="form.introduction"
                :rows="3"
                placeholder="请输入图片简介"
                :maxlength="200"
                show-count
              />
            </a-form-item>

            <!-- 分类 -->
            <a-form-item label="分类" name="category">
              <a-select
                v-model:value="form.category"
                placeholder="请选择分类"
                :loading="loadingTags"
                allow-clear
              >
                <a-select-option
                  v-for="category in categoryList"
                  :key="category"
                  :value="category"
                >
                  {{ category }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <!-- 标签 -->
            <a-form-item label="标签" name="tags">
              <a-select
                v-model:value="form.tags"
                mode="tags"
                placeholder="输入后回车或选择预置标签"
                style="width: 100%"
                :loading="loadingTags"
              >
                <a-select-option
                  v-for="tag in tagList"
                  :key="tag"
                  :value="tag"
                >
                  {{ tag }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <!-- 返回按钮 -->
            <a-form-item :wrapper-col="{ offset: 4 }">
              <a-button @click="$router.back()">返回</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import {
  uploadPictureUsingPost,
  uploadPictureByUrlUsingPost
} from '@/api/pictureController'
import { listCategoryUsingPost } from '@/api/pictureCategoryController.ts'
import { listTagUsingPost } from '@/api/pictureTagController.ts'
import type { UploadProps } from 'ant-design-vue/es/upload/interface'
import { onMounted } from 'vue'

const router = useRouter()

// 表单数据
const form = reactive({
  name: '',
  introduction: '',
  category: undefined as string | undefined,
  tags: [] as string[],
})

const fileList = ref<UploadProps['fileList']>([])
const loadingTags = ref(false)
const loading = ref(false)
const urlLoading = ref(false)
const fileUrl = ref<string>()
const previewUrl = ref<string>()

// 标签和分类数据
const tagList = ref<string[]>([])
const categoryList = ref<string[]>([])

// 监听URL变化，更新预览
watch(fileUrl, (newUrl) => {
  if (newUrl) {
    // 简单验证URL格式
    try {
      new URL(newUrl)
      previewUrl.value = newUrl
    } catch (e) {
      previewUrl.value = ''
    }
  } else {
    previewUrl.value = ''
  }
})

// 文件变化时的处理函数
const handleUploadChange = (info: any) => {
  fileList.value = info.fileList
}

// 获取标签和分类数据
const fetchTagCategories = async () => {
  loadingTags.value = true
  try {
    // 获取所有分类
    const categoryRes = await listCategoryUsingPost({})
    if (categoryRes.data.code === 0) {
      categoryList.value = categoryRes.data.data?.map((item: any) => item.categoryName) || []
    }

    // 获取所有标签
    const tagRes = await listTagUsingPost({})
    if (tagRes.data.code === 0) {
      tagList.value = tagRes.data.data?.map((item: any) => item.tagName) || []
    }
  } catch (error) {
    message.error('获取标签分类失败')
  } finally {
    loadingTags.value = false
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchTagCategories()
})

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }

  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！')
    return false
  }

  // 校验文件格式
  const fileSuffix = file.name.split('.').pop()?.toLowerCase()
  const allowedFormats = ['jpeg', 'jpg', 'png', 'webp']
  if (!fileSuffix || !allowedFormats.includes(fileSuffix)) {
    message.error('只支持 jpg、png、webp 格式的图片！')
    return false
  }

  return false // 阻止自动上传，等待提交时统一处理
}

// 提交表单
const handleSubmit = async () => {
  if (!fileList.value || fileList.value.length === 0) {
    message.warning('请先选择图片')
    return
  }

  const file = fileList.value[0]
  if (!file.originFileObj) {
    message.warning('请选择有效的图片文件')
    return
  }

  loading.value = true
  try {
    // 构建请求参数
    const params = {}

    // 构建请求体 - 对应 PictureUploadRequest
    const pictureUploadRequest = {
        name: form.name,
        introduction: form.introduction,
        category: form.category,
        tags: form.tags,
    }
    // 调用上传接口（一次性完成上传和数据库写入）
    const res = await uploadPictureUsingPost(
      params,
      pictureUploadRequest,
      file.originFileObj
    )
    // console.log(res.data.data)

    if (res.data.code === 0) {
      message.success('图片上传成功！')
      setTimeout(() => {
        router.push('/')
      }, 1500)
    } else {
      message.error(res.data.message || '上传失败')
    }
  } catch (error: any) {
    console.error('上传失败:', error)
    message.error(error.message || '上传失败，请重试')
  } finally {
    loading.value = false
  }
}

// 通过URL上传图片
const handleUploadByUrl = async () => {
  if (!fileUrl.value) {
    message.warning('请输入图片URL')
    return
  }

  // 验证URL格式
  try {
    new URL(fileUrl.value)
  } catch (e) {
    message.error('请输入有效的URL')
    return
  }

  urlLoading.value = true
  try {
    // 构建请求参数
    const pictureUploadRequest = {
      fileUrl: fileUrl.value,
      name: form.name,
      introduction: form.introduction,
      category: form.category,
      tags: form.tags,
    }

    // 调用URL上传接口
    const res = await uploadPictureByUrlUsingPost(pictureUploadRequest)

    if (res.data.code === 0) {
      message.success('图片上传成功！')
      setTimeout(() => {
        router.push('/')
      }, 1500)
    } else {
      message.error(res.data.message || '上传失败')
    }
  } catch (error: any) {
    console.error('上传失败:', error)
    message.error(error.message || '上传失败，请重试')
  } finally {
    urlLoading.value = false
  }
}

</script>

<style scoped>
.upload-tips {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}

.create-picture-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}
</style>
